<?php

namespace common\jobs\handle;

use Yii;
use yii\db\Exception;
use common\models\user\UserBranch;
use common\models\member\Member;
use common\models\member\MemberAccount;
use common\models\member\MemberBranchLog;

/**
 * 会员账户开通任务处理
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class OpenAccountHandle extends \common\jobs\base\BaseJobHandleModel {

    /**
     * @var integer 会员ID
     */
    public $member_id = null;

    /**
     * @var Member|null 会员模型
     */
    public $_model = null;

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['member_id'], 'required'],
            [['member_id'], 'integer'],
            [['member_id'], 'validateMember'],
        ];
    }

    /**
     * 校验订单信息
     * @param string $attribute the attribute currently being validated
     */
    public function validateMember($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $model = Member::findOne($this->$attribute);
        if (!$model) {
            return $this->addError($attribute, '【' . $this->$attribute . '】会员信息不存在！');
        }
        if ($model->account) {
            return $this->addError($attribute, '【' . $this->$attribute . '】已开户！');
        }
        $this->_model = $model;
    }

    /**
     * 获取会员信息
     * @return Member|null
     */
    public function getModel() {
        return $this->_model;
    }

    /**
     * 执行返佣
     * @inheritdoc
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError('返佣操作失败');
        }
        //获取会员信息
        $member = $this->getModel();
        //创建会员账户
        $account = new MemberAccount();
        $account->attributes = [
            'member_id' => $member->id,
            'user_id' => $member->user_id,
            'status' => MemberAccount::STATUS_ACTIVE,
            'deleted_at' => 0,
        ];
        //查询会员之前是否存在归属关系
        $oldBranch = UserBranch::find()->active()->andWhere([
            'user_id' => $member->user_id,
        ])->one();
        //创建会员自身归属关系
        $newBranch = new UserBranch();
        $newBranch->attributes = [
            'user_id' => $member->user_id,
            'member_id' => $member->id,
            'member_user_id' => $member->user_id,
            'status' => UserBranch::STATUS_ACTIVE,
        ];

        //开启事务保存
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$account->save()) {
                throw new Exception($account->getErrorMsg());
            }
            //如存在会员归属则屏蔽原有归属
            if ($oldBranch) {
                $oldBranch->deleted_at = time();
                if (!$oldBranch->save()) {
                    throw new Exception($oldBranch->getErrorMsg());
                }
                $branchLog = new MemberBranchLog();
                $branchLog->setTypeLog(MemberBranchLog::TYPE_RELEASE, $oldBranch);
                if (!$branchLog->save()) {
                    throw new Exception($branchLog->getErrorMsg());
                }
            }
            if (!$newBranch->save()) {
                throw new Exception($newBranch->getErrorMsg());
            }
            $branchLog = new MemberBranchLog();
            $branchLog->setTypeLog(MemberBranchLog::TYPE_GROWUP, $newBranch);
            if (!$branchLog->save()) {
                throw new Exception($branchLog->getErrorMsg());
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            return $this->dumpRetryError($e->getMessage());
        }
        return $this->dumpSuccess([
            'MemberId' => $member->id,
            'UserId' => $member->user_id,
            'Message' => '会员开户成功！',
        ]);
    }

}
